package com.gx.smart.building.ui.login.fragment;

import android.content.Intent;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.SPUtils;
import com.gx.smart.base.BaseMVVMFragment;
import com.gx.smart.building.R;
import com.gx.smart.building.databinding.LoginFragmentBinding;
import com.gx.smart.building.ui.home.activity.MainActivity;
import com.gx.smart.building.ui.login.viewmodel.LoginViewModel;
import com.gx.smart.common.util.AppConfig;
import com.mylhyl.circledialog.CircleDialog;
import com.orhanobut.logger.Logger;

public class LoginFragment extends BaseMVVMFragment<LoginFragmentBinding, LoginViewModel> {

    private final TimeCount mTime = new TimeCount(60 * 1000, 1000);

    //获取验证码定时器
    private class TimeCount extends CountDownTimer {
        private TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            binding.verifyCodeTextView.setText("获取验证码");
            viewModel.verifyCodeEnable.set(true);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            binding.verifyCodeTextView.setText(String.format("%s", millisUntilFinished / 1000 + "s"));
        }
    }


    @Override
    protected Class<LoginViewModel> onBindViewModel() {
        return LoginViewModel.class;
    }

    @Override
    protected LoginFragmentBinding onBindViewBinding(@NonNull LayoutInflater inflater, @Nullable ViewGroup parent, boolean attachToParent) {
        return DataBindingUtil.inflate(inflater, R.layout.login_fragment, parent, false);
    }

    @Override
    protected void initView(@NonNull View view) {
        binding.setLifecycleOwner(getViewLifecycleOwner());
        binding.setLoginFragment(this);
        binding.setViewModel(viewModel);
        String account = SPUtils.getInstance().getString(AppConfig.LOGIN_ACCOUNT, "");
        viewModel.phoneNumber.set(account);
    }

    public void login(View v) {
        if (!verifyNetworkPhone()) {
            return;
        }
        if (viewModel.tabIndex.get() == 0) {
            String password = binding.password.getText().toString().trim();
            if (TextUtils.isEmpty(password)) {
                new CircleDialog.Builder()
                        .setTitle("提示")
                        .setText("密码不能为空")
                        .setPositive("确定", null)
                        .show(getActivity().getSupportFragmentManager());
                return;
            }

            if (password.length() < 6 || password.length() > 18) {
                new CircleDialog.Builder()
                        .setTitle("提示")
                        .setText("账号或者密码错误")
                        .setPositive("确定", null)
                        .show(getActivity().getSupportFragmentManager());
                return;
            }
            //密码登录
            login(password, 1);
        } else {
            String verifyCode = binding.verifyCode.getText().toString().trim();

            if (TextUtils.isEmpty(verifyCode)) {
                new CircleDialog.Builder()
                        .setTitle("提示")
                        .setText("验证码不能为空")
                        .setPositive("确定", null)
                        .show(getActivity().getSupportFragmentManager());
                return;
            }
            //验证码登录
            login(verifyCode, 3);
        }
    }


    private void login(String passwordOrVerifyCode, int loginType) {
        viewModel.login(viewModel.phoneNumber.get().trim(), passwordOrVerifyCode, loginType).observe(getViewLifecycleOwner(), result -> {
                    if (result) {
                        ActivityUtils.startActivity(new Intent(getActivity(), MainActivity.class));
                        getActivity().finish();
                    }
                }
        );
    }


    private Observer<Boolean> verifyCodeObserver;

    public void getVerifyCode(View v) {

        if (!verifyNetworkPhone()) {
            return;
        }
        viewModel.verifyCodeEnable.set(false);
        if (verifyCodeObserver == null) {
            verifyCodeObserver = result -> {
                Logger.e("verifyCodeObserver:" + verifyCodeObserver + " result:" + result);
                if (result) {
                    mTime.start();
                } else {
                    viewModel.verifyCodeEnable.set(true);
                }
            };
        }
        viewModel.getVerifyCode(viewModel.phoneNumber.get().trim()).observe(getViewLifecycleOwner(), verifyCodeObserver);
    }

    //通过为true 否则 false
    private boolean verifyNetworkPhone() {
        if (!NetworkUtils.isConnected()) {
            new CircleDialog.Builder()
                    .setTitle("提示")
                    .setText("网络连接不可用")
                    .setPositive("确定", null)
                    .show(getActivity().getSupportFragmentManager());
            return false;
        }

        String phone = viewModel.phoneNumber.get().trim();
        if (TextUtils.isEmpty(phone)) {
            new CircleDialog.Builder()
                    .setTitle("提示")
                    .setText("账号不能为空")
                    .setPositive("确定", null)
                    .show(getActivity().getSupportFragmentManager());
            return false;
        }
//        if (!RegexUtils.isMobileExact(phone)) {
//            new CircleDialog.Builder()
//                    .setTitle("提示")
//                    .setText("非法手机号")
//                    .setPositive("确定", null)
//                    .show(getActivity().getSupportFragmentManager());
//            return false;
//        }
        return true;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mTime.cancel();
    }

}
